<template>
  <div id="app1">
    <div class="container">
      <div class="main-content">
        <!-- 左侧数据面板 -->
        <div class="panel left-panel">
          <h2 class="panel-title leftData">GXJG_JZG（教师数据）</h2>
          <div class="items-container">
            <div v-for="(item, _index) in leftItems" :key="'left-' + item.id" class="item selectedLeft"
              :class="{ selected: item.selected, connectedLeft: item.connections.length > 0 }"
              @click="selectItem('left', item)" @dblclick="removeConnections(item)">
              <div class="item-content">
                <div class="item-title text">{{ item.title }}</div>
                <div class="item-desc text">{{ item.description }}</div>
              </div>
            </div>
          </div>
        </div>
        <!-- 右侧数据面板 -->
        <div class="panel right-panel">
          <h2 class="panel-title rightData">GXJG_JZG（教师数据）</h2>
          <div class="items-container">
            <div v-for="(item, _index) in rightItems" :key="'right-' + item.id" class="item selectedRigth"
              :class="{ selected: item.selected, connectedRight: isRightItemConnected(item.id) }"
              @click="selectItem('right', item)">
              <div class="item-content">
                <div class="item-title text">{{ item.title }}</div>
                <div class="item-desc text">{{ item.description }}</div>
              </div>
            </div>
          </div>
        </div>
        <!-- SVG连线容器 -->

        <svg class="connections-container" ref="connectionsContainer">
          <defs>
            <marker id="arrowhead" markerWidth="10" markerHeight="7" refX="9" refY="3.5" orient="auto">
              <polygon points="0 0, 10 3.5, 0 7" fill="#333333" />
            </marker>
          </defs>
          <line v-for="(connection, index) in connections" :key="index" class="connection-line" :x1="connection.x1"
            :y1="connection.y1" :x2="connection.x2" :y2="connection.y2" marker-end="url(#arrowhead)" />
        </svg>
      </div>
      <!-- <div class="controls">
        <button class="btn btn-primary" @click="addLeftItem">
          <i class="fas fa-plus"></i> 添加左侧数据
        </button>
        <button class="btn btn-primary" @click="addRightItem">
          <i class="fas fa-plus"></i> 添加右侧数据
        </button>
        <button class="btn btn-danger" @click="resetAll">
          <i class="fas fa-trash"></i> 重置所有数据
        </button>
      </div> -->

      <!-- <div class="status-bar">
        <i class="fas fa-info-circle"></i>
        <span v-if="connections.length === 0">请选择左侧和右侧的数据项来创建连线</span>
        <span v-else>已创建 {{ connections.length }} 条数据连接</span>
      </div> -->
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue';
// 数据状态
const leftItems: any = ref([
  { id: 1, title: 'GXJG_ZG', description: '教师数据', selected: false, connections: [] },
  { id: 2, title: 'GH', description: '工号', selected: false, connections: [] },
  { id: 3, title: 'XM', description: '姓名', selected: false, connections: [] },
  { id: 4, title: 'XB', description: '性别', selected: false, connections: [] },
  { id: 5, title: 'CSNY', description: '出生年月', selected: false, connections: [] },
  { id: 6, title: 'CSNY', description: '出生年月', selected: false, connections: [] },
  { id: 7, title: 'CSNY', description: '出生年月', selected: false, connections: [] },
  { id: 8, title: 'CSNY', description: '出生年月', selected: false, connections: [] },
  { id: 9, title: 'CSNY', description: '出生年月', selected: false, connections: [] },

]);

const rightItems: any = ref([
  { id: 1, title: 'GXJG_ZG', description: '教师数据', selected: false },
  { id: 2, title: 'GH', description: '工号', selected: false },
  { id: 3, title: 'XM', description: '姓名', selected: false },
  { id: 4, title: 'XB', description: '性别', selected: false },
  { id: 5, title: 'CSNY', description: '出生年月', selected: false },
  { id: 6, title: 'CSNY', description: '出生年月', selected: false, },
  { id: 7, title: 'CSNY', description: '出生年月', selected: false, },
  { id: 8, title: 'CSNY', description: '出生年月', selected: false, },
  { id: 9, title: 'CSNY', description: '出生年月', selected: false, },
]);

const connections: any = ref([]);
const lastSelected: any = ref({ left: null, right: null });
const connectionsContainer: any = ref(null);
const resizeObserver: any = ref(null);


// 方法
const selectItem = (side: any, item: any) => {
  // 清除所有选中状态
  if (side === 'left') {
    leftItems.value.forEach((i: any) => i.selected = false);
    rightItems.value.forEach((i: any) => i.selected = false);
    item.selected = true;
    lastSelected.value.left = item;
  } else {
    if (!lastSelected.value.left) return;

    rightItems.value.forEach((i: any) => i.selected = false);
    item.selected = true;
    lastSelected.value.right = item;

    // 建立连接
    createConnection();
  }
};

const createConnection = () => {
  if (!lastSelected.value.left || !lastSelected.value.right) return;

  // 检查连接是否已存在
  const connectionExists = lastSelected.value.left.connections.includes(lastSelected.value.right.id);
  if (!connectionExists) {
    lastSelected.value.left.connections.push(lastSelected.value.right.id);
  }

  // 更新连线
  updateConnections();

  // // 重置选中状态但保留连接
  // setTimeout(() => {
  //   lastSelected.value.left.selected = false;
  //   lastSelected.value.right.selected = false;
  //   lastSelected.value = { left: null, right: null };
  // }, 500);
};

const removeConnections = (item: any) => {
  item.connections = [];
  updateConnections();
};

const updateConnections = () => {
  connections.value = [];

  leftItems.value.forEach((leftItem: any) => {
    leftItem.connections.forEach((rightId: any) => {
      const rightItem = rightItems.value.find((item: any) => item.id === rightId);
      console.log(rightItem, 123, rightId, leftItem.id);

      if (rightItem) {
        const leftIndex = leftItems.value.findIndex((item: any) => item.id === leftItem.id);
        const rightIndex = rightItems.value.findIndex((item: any) => item.id === rightId);

        const leftElement = document.querySelectorAll('.left-panel .item')[leftIndex];
        const rightElement = document.querySelectorAll('.right-panel .item')[rightIndex];

        if (leftElement && rightElement && connectionsContainer.value) {
          const leftRect = leftElement.getBoundingClientRect();
          const rightRect = rightElement.getBoundingClientRect();
          const containerRect = connectionsContainer.value.getBoundingClientRect();

          connections.value.push({
            x1: leftRect.right - containerRect.left + 15,
            y1: leftRect.top + leftRect.height / 2 - containerRect.top,
            x2: rightRect.left - containerRect.left - 15,
            y2: rightRect.top + rightRect.height / 2 - containerRect.top
          });
        }
      }
    });
  });



};

const isRightItemConnected = (id: never | number) => {
  return leftItems.value.some((leftItem: any) => leftItem.connections.includes(id));
};

// const addLeftItem = () => {
//   const newId = leftItems.value.length > 0
//     ? Math.max(...leftItems.value.map(item => item.id)) + 1
//     : 1;

//   const titles = ['库存管理', '物流追踪', '客户支持', '营销活动'];
//   const descriptions = ['跟踪产品库存情况', '监控物流运输状态', '处理客户问题和反馈', '管理营销推广活动'];

//   const randomIndex = Math.floor(Math.random() * titles.length);

//   leftItems.value.push({
//     id: newId,
//     title: titles[randomIndex],
//     description: descriptions[randomIndex],
//     selected: false,
//     connections: []
//   });
// };

// const addRightItem = () => {
//   const newId = rightItems.value.length > 0
//     ? Math.max(...rightItems.value.map(item => item.id)) + 1
//     : 1;

//   const titles = ['API网关', '缓存服务', '身份认证', '日志系统'];
//   const descriptions = ['管理API请求路由', '提供高速数据缓存', '处理用户认证授权', '收集和分析日志数据'];

//   const randomIndex = Math.floor(Math.random() * titles.length);

//   rightItems.value.push({
//     id: newId,
//     title: titles[randomIndex],
//     description: descriptions[randomIndex],
//     selected: false
//   });
// };

// const resetAll = () => {
//   leftItems.value.forEach(item => {
//     item.selected = false;
//     item.connections = [];
//   });
//   rightItems.value.forEach(item => item.selected = false);
//   connections.value = [];
//   lastSelected.value = { left: null, right: null };
// };

// 初始化FontAwesome样式
// const style = document.createElement('style');
// style.innerHTML = `
//   .fa, .fas {
//     font-family: 'Font Awesome 5 Free';
//     font-weight: 900;
//     display: inline-block;
//     font-style: normal;
//     font-variant: normal;
//     text-rendering: auto;
//     line-height: 1;
//     width: 1em;
//   }
//   .fa-plus:before { content: "\\f067"; }
//   .fa-trash:before { content: "\\f1f8"; }
//   .fa-info-circle:before { content: "\\f05a"; }
// `;
// document.head.appendChild(style);

// 初始连线示例
onMounted(() => {
  resizeObserver.value = new ResizeObserver(() => {
    updateConnections();
  });

  if (connectionsContainer.value) {
    resizeObserver.value.observe(connectionsContainer.value);
  }
  setTimeout(() => {
    leftItems.value[0].connections.push(1);
    leftItems.value[0].connections.push(2);
    leftItems.value[1].connections.push(3);
    updateConnections();
  }, 500);
});
onUnmounted(() => {
  if (resizeObserver.value) {
    resizeObserver.value.disconnect();
  }
});
</script>

<style scoped lang="scss">
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

body {
  font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
  background: linear-gradient(135deg, #1a2a6c, #b21f1f, #1a2a6c);
  color: #333;
  min-height: 100vh;
  padding: 20px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.container {
  width: 100%;
  border-radius: 15px;
  overflow: hidden;
  padding: 25px;
}

header {
  text-align: center;
  margin-bottom: 30px;
  padding: 20px 0;
  border-bottom: 2px solid #eaeaea;
}

h1 {
  font-size: 2.5rem;
  color: #2c3e50;
  margin-bottom: 10px;
  text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.1);
}



.connectedLeft {
  position: relative;

  &::after {
    content: "";
    position: absolute;
    right: -15px;
    top: 50%;
    transform: translateY(-50%);
    width: 15px;
    height: 15px;
    background: linear-gradient(180deg, #2EAC46, #35A74A, #64B646, #AAD140);
    border-radius: 50%;
    z-index: 11;
  }
}

.connectedRight {
  position: relative;

  &::after {
    content: "";
    position: absolute;
    left: -15px;
    top: 50%;
    transform: translateY(-50%);
    width: 15px;
    height: 15px;
    background: linear-gradient(180deg, #E7A20E, #EBB205, #FCCA00, #FFD52B);
    border-radius: 50%;
    z-index: 11;
  }
}


.subtitle {
  font-size: 1.1rem;
  color: #7f8c8d;
  max-width: 700px;
  margin: 0 auto;
  line-height: 1.6;
}

.main-content {
  display: flex;
  justify-content: space-between;

  position: relative;
}

.panel {

  width: 337px;
  box-sizing: border-box;
  font-family: Microsoft YaHei;
  font-weight: 400;
  font-size: 14px;
  color: #FFFFFF;
  line-height: 40px;
}

.leftData {
  width: 100%;
  padding: 0 20px;
  border-radius: 5px 5px 0 0;
  background: linear-gradient(180deg, #2EAC46, #35A74A, #64B646, #AAD140);
}

.rightData {
  width: 100%;
  padding: 0 20px;
  border-radius: 5px 5px 0 0;
  background: linear-gradient(180deg, #E7A20E, #EBB205, #FCB800, #FFD52B);
}







.counter {
  background: #2980b9;
  color: white;
  border-radius: 50%;
  width: 30px;
  height: 30px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: bold;
}

.items-container {
  width: 100%;
  min-height: 258px;
  background: #FFFFFF;
  box-shadow: 1px 1px 5px 0px rgba(0, 0, 0, 0.15);
  border-radius: 0 0 5px 5px;
  color: #333;
  padding: 0 10px;
  cursor: pointer;
}

.item {
  min-height: 40px;
  display: flex;
  align-items: center;
  font-family: Microsoft YaHei;
  font-weight: 400;
  font-size: 14px;
  color: #333333;
  padding: 0 10px;
}

.selectedRigth.selected {
  background-color: #FFECCC;
}

.selectedLeft.selected {
  background-color: rgb(0, 182, 39, 0.2);
}



.item-icon {
  width: 40px;
  height: 40px;
  background: #2980b9;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 15px;
  color: white;
  font-weight: bold;
  flex-shrink: 0;
}

.item-content {
  flex-grow: 1;
  display: flex;
  align-items: center;

  .text {
    width: calc(100% / 2);
    font-family: Microsoft YaHei;
    font-weight: 400;
    font-size: 14px;
    color: #333333;
  }

  & .text:nth-child(2) {
    text-align: right;
  }
}

.item-title {
  font-weight: bold;
  font-size: 1.1rem;
  margin-bottom: 5px;
  color: #2c3e50;
}

.item-desc {
  color: #7f8c8d;
  font-size: 0.9rem;
}



.connections-container {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  pointer-events: none;
  z-index: 1;
}

.connection-line {
  stroke: #333;
  stroke-width: 1;
  animation: dash 1s linear infinite;
}

@keyframes dash {
  to {
    stroke-dashoffset: -20;
  }
}

.controls {
  display: flex;
  justify-content: center;
  gap: 15px;
  margin-top: 30px;
  flex-wrap: wrap;
}



.status-bar {
  text-align: center;
  margin-top: 20px;
  padding: 15px;
  background: #e3f2fd;
  border-radius: 8px;
  font-size: 1.1rem;
  font-weight: 500;
  color: #2980b9;
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 10px;
}

.instructions {
  background: #fff9db;
  border-left: 4px solid #f59f00;
  padding: 15px;
  border-radius: 0 8px 8px 0;
  margin: 25px 0;
  font-size: 0.95rem;
  color: #5c3c00;
}

.instructions h3 {
  margin-bottom: 10px;
  color: #e67700;
}

.instructions ul {
  padding-left: 20px;
}

.instructions li {
  margin-bottom: 8px;
}
</style>